package com.woniu.util;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;

/**
 * 发送电子邮箱的
 */
public class SendEmail {

    public static void main(String[] args) throws Exception {
        sendEmail();
    }

    // 模板代码拷贝过来
    public static void sendEmail() throws Exception {

        /***********************1、注册服务信息***********************************/

        Properties props = new Properties();
        // 开启debug调试
        props.setProperty("mail.debug", "true");
        // 发送服务器需要身份验证
        props.setProperty("mail.smtp.auth", "true");
        // 设置邮件服务器主机名
        props.setProperty("mail.host", "smtp.qq.com");
        // 发送邮件协议名称
        props.setProperty("mail.transport.protocol", "smtp");

        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);

        // 根据propertise创建会话 javax.mail
        Session session = Session.getInstance(props);

        /***********************2、创建消息对象***********************************/
        Message msg = new MimeMessage(session);
        msg.setSubject("hello，我爱你❤"); // 设置邮件的标题
        msg.setFrom(new InternetAddress("434679924@qq.com"));

        // TODO

        MimeBodyPart tx = new MimeBodyPart();
        tx.setContent("<h1>我爱你❤<h1>","text/html;charset=utf-8");

        // 放到根节点MimeMultipart
        MimeMultipart root = new MimeMultipart();
        root.addBodyPart(tx);

        // 把根节点放到msg对象里面
        msg.setContent(root);


        /***********************3、开启会话传输***********************************/

        // 开始会话传输
        Transport transport = session.getTransport();
        // 连接邮箱   加入自己（发送方）授权码
        transport.connect("smtp.qq.com", "434679924@qq.com", "cyzmamxodlrvbidi");

        // 给目标邮箱发送邮件
        transport.sendMessage(msg, new Address[] { new InternetAddress("434679924@qq.com") });
        transport.close();

    }
}
